//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Windows.Forms;

namespace PreflightClientTool
{
    using System.Collections.Generic;
    using System.Security.Cryptography.X509Certificates;
    using System.Xml.Linq;
    using Preflight.Security;
    using Preflight.ServiceModel.Client;

    public partial class EditEndpointForm : Form
    {
        private Dictionary<int, Func<string>> templateIndexToFactoryMethodMapping;

        public EditEndpointForm()
        {
            InitializeComponent();
        }

        private Dictionary<int, Func<string>> TemplateIndexToFactoryMethodMapping
        {
            get
            {
                if (this.templateIndexToFactoryMethodMapping == null)
                {
                    this.templateIndexToFactoryMethodMapping = BuildTemplateFactoryMethodMapping();
                }

                return this.templateIndexToFactoryMethodMapping;
            }
        }

        private void HandleFormLoad(object sender, EventArgs e)
        {

        }

        public static bool EditTarget(Target target)
        {
            var form = new EditEndpointForm
                {
                    templates =
                        {
                            Visible = false
                        },
                    endpointXml =
                        {
                            Text = target.Endpoint.ToXml().ToString()
                        }
                };

            if (form.ShowDialog() == DialogResult.OK)
            {
                var xml = XElement.Parse(form.endpointXml.Text);
                target.Endpoint = EndpointDescription.CreateFromXml(xml);
                return Try.Action(() => PreflightFacade.UpsertTarget(target));
            }

            return false;
        }

        public static Target CreateNewTarget()
        {
            var form = new EditEndpointForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                var xml = XElement.Parse(form.endpointXml.Text);
                var endpoint = EndpointDescription.CreateFromXml(xml);
                var target = new Target
                    {
                        Endpoint = endpoint,
                        State = TargetState.Unknown
                    };

                if(Try.Action(() => PreflightFacade.UpsertTarget(target)))
                {
                    return target;
                }
            }

            return null;
        }

        private void HandleTemplateSelected(object sender, EventArgs e)
        {
            if (this.TemplateIndexToFactoryMethodMapping.ContainsKey(this.templates.SelectedIndex))
            {
                this.endpointXml.Text = this.TemplateIndexToFactoryMethodMapping[this.templates.SelectedIndex]();
            }
            else
            {
                this.endpointXml.Text = string.Empty;
            }
        }

        private Dictionary<int, Func<string>> BuildTemplateFactoryMethodMapping()
        {
            var uri = new Uri("http://temp.org");
            var mapping = new Dictionary<int, Func<string>>();
            mapping[1] = () => CreateTemplate(factory => factory.CreateUnsecureHttpDescription(CreateUniqueName(), uri));
            mapping[2] = () => CreateTemplate(factory => factory.CreateSecureHttpDescription(CreateUniqueName(), uri, new CertificateLocation(StoreLocation.LocalMachine, StoreName.My, "REAL-THUMBPRINT-HERE")));
            mapping[3] = () => CreateTemplate(factory => factory.CreateWindowsAuthenticationEndpointDescription(CreateUniqueName(), uri));
            return mapping;
        }

        private static string CreateTemplate(Func<StandardEndpointFactory, EndpointDescription> createEndpoint)
        {
            var factory = new StandardEndpointFactory();
            return createEndpoint(factory).ToXml().ToString();
        }

        private static string CreateUniqueName()
        {
            return string.Format("Endpoint {0}", DateTime.Now);
        }
    }
}
